package com.feng.demo.xstream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class Employee {
	private String name;
	private String designation;
	private String department;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	@Override
	public String toString() {
		return "Name : " + this.name + "\nDesignation : " + this.designation
				+ "\nDepartment : " + this.department;
	}

	/**
	 * 使用XStream由XML生成JavaObject
	 * 
	 * @author 刘兵召
	 * 
	 */
	public static void Reader() {
		XStream xs = new XStream(new DomDriver());
		Employee e = new Employee();
		xs.alias("Employee", Employee.class);
		try {
			FileInputStream in = new FileInputStream("d:/employeedata.xml");
			InputStreamReader reader = new InputStreamReader(in,
					Charset.forName("UTF-8"));
			xs.fromXML(reader, e);
			System.out.println(e.toString());
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 使用XStream由JavaObject生成XML
	 * 
	 * @author 刘兵召
	 * @throws IOException 
	 * 
	 */
	public static void Writer() throws IOException {
		Employee e = new Employee();
		e.setName("Jack中国");
		e.setDesignation("Manager");
		e.setDepartment("Finance");
		XStream xs = new XStream();
		xs.alias("Employee", Employee.class);
		try {
			FileOutputStream out = new FileOutputStream("d:/employeedata.xml");
			OutputStreamWriter writer = new OutputStreamWriter(out,
					Charset.forName("UTF-8"));
			writer.write("<!--l version=\"1.0\" encoding=\"UTF-8\"-->\n");
			xs.toXML(e, writer);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws IOException {
		Reader();
		Writer();
	}
}
